var dlmModule = angular.module('dlmApp', ['ngRoute', 'ngCookies'],
    function ($routeProvider) {
        $routeProvider.when('/index', {
            templateUrl: 'views/itemList.html',
            controller: 'ItemListCtrl',
            title: '大脸猫-美容'
        }).when('/reg', {
            templateUrl: 'views/reg.html',
            controller: 'regCtrl'
        }).when('/item/:itemId/:tiId/:techId', {
            templateUrl: 'views/itemshow.html',
            controller: 'ItemShow'
        }).when('/designer', {
            templateUrl: 'views/designerlist.html',
            controller: 'DesignerCtrl',
            title: '大脸猫-美容'
        }).when('/designer/:designerId', {
            templateUrl: 'views/designershow.html',
            controller: 'DesignerShowCtrl'
        }).when('/user/home', {
            templateUrl: 'views/userhome.html',
            controller: 'UserHomeCtrl',
            title: '个人中心'
        }).when('/selectTech', {
            templateUrl: 'views/selectTech.html',
            controller: 'SelectTechCtrl',
            title: '选择店面'
        }).when('/oStep1', {
            templateUrl: 'views/oStep1.html',
            controller: 'OrderStep1Ctrl',
            title: '填写订单信息'
        }).when('/oStep2', {
            templateUrl: 'views/oStep2.html',
            controller: 'OrderStep2Ctrl',
            title: '填写时间'
        }).when('/oStep3', {
            templateUrl: 'views/oStep3.html',
            controller: 'OrderStep3Ctrl',
            title: '提交订单'
        }).when('/user/order', {
            templateUrl: 'views/userorder.html',
            controller: 'UserOrderCtrl',
            title: '我的订单',
            showBackBtn: !0,
            hideFooter: !0
        }).when('/user/orderDetail/:orderId', {
            templateUrl: 'views/orderDetail.html',
            controller: 'OrderDetailCtrl',
            title: '订单详情'
        }).when('/user/coupon', {
            templateUrl: 'views/coupon.html',
            controller: 'CouponCtrl',
            title: '我的优惠券',
            showBackBtn: !0,
            hideFooter: !0
        }).otherwise({
            redirectTo: '/index'
        })
    }
);

dlmModule.constant('pageSize', 10);
dlmModule.value('city', [{
    'name': '北京',
    id: 1,
    'dict': [
        {'name': "昌平区", 'id': 1},
        {'name': "朝阳区", 'id': 2},
        {'name': "崇文区", 'id': 3},
        {'name': "大兴区", 'id': 4},
        {'name': "东城区", 'id': 5},
        {'name': "房山区", 'id': 6},
        {'name': "丰台区", 'id': 7},
        {'name': "海淀区", 'id': 8},
        {'name': "怀柔区", 'id': 9},
        {'name': "经济技术开发区", 'id': 10},
        {'name': "门头沟区", 'id': 11},
        {'name': "平谷区", 'id': 12},
        {'name': "石景山区", 'id': 12},
        {'name': "顺义区", 'id': 12},
        {'name': "通州区", 'id': 12},
        {'name': "宣武区", 'id': 13}
    ]
}]);

///////////////////////controller//////////////////////////////////
dlmModule.controller('ItemListCtrl', [
    '$rootScope',
    '$scope',
    '$http',
    'pageSize',
    'User',
    '$timeout',
    '$cookies',
    'SerData',
    '$window',
    function (a, b, c, d, e, f, g, h, i) {
        g.longitude && g.latitude ? (e.setInfo('longitude', parseFloat(g.longitude)), e.setInfo('latitude', parseFloat(g.latitude))) : navigator.geolocation && navigator.geolocation.getCurrentPosition(function (a) {
            console.log('get position'),
                e.setInfo('longitude', a.coords.longitude),
                e.setInfo('latitude', a.coords.latitude),
                e.setInfo('longitudeD', a.coords.longitude),
                e.setInfo('latitudeD', a.coords.latitude),
                g.longitude = a.coords.longitude + '',
                g.latitude = a.coords.latitude + '',
                g.longitudeD = a.coords.longitude + '',
                g.latitudeD = a.coords.latitude + '',
                i.location.reload()
        }, function () {
            console.log('error position', e.info),
                e.setInfo('longitude', e.info.longitude),
                e.setInfo('latitude', e.info.latitude),
                e.setInfo('longitudeD', e.info.longitudeD),
                e.setInfo('latitudeD', e.info.latitudeD),
                g.longitude = e.info.longitude + '',
                g.latitude = e.info.latitude + '',
                g.longitudeD = e.info.longitudeD + '',
                g.latitudeD = e.info.latitudeD + '',
                i.location.reload()
        }, {
            enableHighAcuracy: !0,
            timeout: 5000
        }),
            b.title = '大脸猫·上门美容第一大！';
        var j = 0;
        b.city = g.city || '',
            b.code = g.code || '',
            b.products = [],
            b.productloaded = !1,
            b.loaded = !1,
            b.imgHeight = (document.body.offsetWidth - 18) / 2,
            0 == b.city || '' == b.city || 0 == b.city || void 0 == b.city ? (b.city = e.getInfo('city'), b.code = e.getInfo('code'), g.longitude = e.getInfo('longitude') + '', g.latitude = e.getInfo('latitude') + '', c.get('/zmw/weixin/get_location?longitude=' + e.getInfo('longitude') + '&latitude=' + e.getInfo('latitude')).success(function (a) {
                angular.isObject(a) && (b.city = a.city, b.code = a.city_code, g.city = a.city, g.code = a.city_code + '', g.town = a.district, g.province = a.province, e.setInfo('city', a.city), e.setInfo('code', a.city_code), e.setInfo('town', a.district), e.setInfo('province', a.province))
            }), g.longitudeD = e.getInfo('longitudeD') + '', g.latitudeD = e.getInfo('latitudeD') + '', c.get('/zmw/weixin/get_location?longitude=' + e.getInfo('longitudeD') + '&latitude=' + e.getInfo('latitudeD')).success(function (a) {
                angular.isObject(a) && (g.cityD = a.city, g.codeD = a.city_code + '', g.townD = a.district, g.provinceD = a.province, e.setInfo('cityD', a.city), e.setInfo('codeD', a.city_code), e.setInfo('townD', a.district), e.setInfo('provinceD', a.province))
            })) : (e.setInfo('city', g.city), e.setInfo('code', g.code), e.setInfo('town', g.town), e.setInfo('province', g.province), e.setInfo('longitude', g.longitude), e.setInfo('latitude', g.latitude));
        var k = function () {
            var d = 0 == j ? h.indexPageSize : 100,
                g = e.getInfo('longitude'),
                i = e.getInfo('latitude'),
                k = e.getInfo('code');
            a.showAppload = !0,
                c.get('/item/find?psize=' + d + '&city=' + k + '&posX=' + g + '&posY=' + i + '&artisan_id=all&pno=' + ++j).success(function (c) {
                    'ok' == c.message ? (c.data.forEach(function (a) {
                        b.products.push(a)
                    }), c.data.length > 0 ? (b.loading = !1, b.loadingMsg = '', b.loaded = c.data.length >= d ? !0 : !1) : (b.loadingMsg = '没有更多', f(function () {
                        b.loading = !1,
                            b.hasMore = !1,
                            b.loaded = !1
                    }, 2000)), a.showAppload = !1, h.indexPageSize = b.products.length > 100 ? b.products.length : 100) : (b.loadingMsg = '没有更多', f(function () {
                        b.loading = !1,
                            b.hasMore = !1,
                            b.loaded = !1
                    }, 2000), a.showAppload = !1, console.log('data', c)),
                        b.productloaded = !0
                }).error(function () {
                    b.productloaded = !0,
                        b.loadingMsg = '加载失败',
                        f(function () {
                            b.loading = !1,
                                b.hasMore = !1
                        }, 2000)
                })
        };
        k(),
            b.$on('loadmore', function () {
                b.loading || 0 === b.products.length || (b.loading = !0, b.loadingMsg = '加载更多', k('all'))
            }),
            b.loadmoreHandler = function () {
                b.loading || 0 === b.products.length || (b.loading = !0, k('all'))
            }
    }
]);
dlmModule.controller('DesignerCtrl', [
    '$scope',
    '$http',
    'pageSize',
    'User',
    '$timeout',
    '$cookies',
    function (a, b, c, d, e, f) {
        f.longitude && f.latitude ? (d.setInfo('longitude', parseFloat(f.longitude)), d.setInfo('latitude', parseFloat(f.latitude))) : navigator.geolocation && navigator.geolocation.getCurrentPosition(function (a) {
            console.log('get position'),
                d.setInfo('longitude', a.coords.longitude),
                d.setInfo('latitude', a.coords.latitude),
                d.setInfo('longitudeD', a.coords.longitude),
                d.setInfo('latitudeD', a.coords.latitude),
                f.longitude = a.coords.longitude + '',
                f.latitude = a.coords.latitude + '',
                f.longitudeD = a.coords.longitude + '',
                f.latitudeD = a.coords.latitude + '',
                $window.location.reload()
        }, function () {
            console.log('error position', d.info),
                d.setInfo('longitude', d.info.longitude),
                d.setInfo('latitude', d.info.latitude),
                d.setInfo('longitudeD', d.info.longitudeD),
                d.setInfo('latitudeD', d.info.latitudeD),
                f.longitude = d.info.longitude + '',
                f.latitude = d.info.latitude + '',
                f.longitudeD = d.info.longitudeD + '',
                f.latitudeD = d.info.latitudeD + '',
                $window.location.reload()
        }, {
            enableHighAcuracy: !0,
            timeout: 5000
        });
        var g = 1;
        a.loading = !1,
            a.artis = [];
        var h = function () {
            var h = f.code || d.getInfo('code');
            b.get('/tech/find?pno=' + g++ + '&psize=' + c + '&city=' + h + '&posX=' + d.getInfo('longitude') + '&posY=' + d.getInfo('latitude')).success(function (b) {
                '0' == b.code && (b.data.length > 0 ? angular.forEach(b.data, function (b) {
                    a.artis.push(b),
                        a.loading = !1
                }) : (a.loadingMsg = '没有更多', e(function () {
                    a.loading = !1,
                        a.hasMore = !1
                }, 2000)))
            }).error(function () {
                console.log("请求tech异常!");
            })
        };
        h(),
            a.$on('loadmore', function () {
                a.loading || 0 === a.artis.length || (a.loading = !0, a.loadingMsg = '加载更多', h())
            })
    }
]);

dlmModule.controller('DesignerShowCtrl',
    function ($scope,$routeParams,$cookieStore, $http) {
        var techId = $routeParams.designerId;
        var l = 0;
        $scope.selectItem = {};
        $http.get('/tech/findById?id=' + techId).success(function (result) {
            if ('ok' == result.message) {
                $scope.art = result.data;
            }
        });
        var index = {};
        $http.get('/item/find?psize=' + 20 + '&techId=' + techId + '&pno=' + l++).success(function (result) {
            if('ok' == result.message){
                var index = {};
                $scope.products = result.data;
            }
        });
        $scope.next = function(){
            if($scope.selectItem.tiId == undefined){
                alert("请选择项目！");
                return;
            }
            var itemId;
            $.each($scope.products,function(i,data){
                if(data.ti_id ==  $scope.selectItem.tiId){
                    itemId = data.itemId;
                }
            });
            window.location.href = "#/item/" + itemId + "/" + $scope.selectItem.tiId + "/" +　techId;
        };
    });

// 技师详情
//dlmModule.controller('DesignerShowCtrl', [
//    '$scope',
//    '$routeParams',
//    '$http',
//    'User',
//    'Util',
//    'imgShow',
//    '$location',
//    'pageSize',
//    '$timeout',
//    '$cookies',
//    function (a, b, c, d, e, f, g, h, i, j) {
//        var k = b.designerId;
//        a.backPath = '';
//        var l = 0;
//        a.next = function(){
//            if(a.selectItemId == undefined){
//                alert("请选择项目！");
//                return;
//            }
//            window.location.href = "#/item/" + a.itemId + "/" +　b.designerId;
//        };
//        a.city = j.city || '',
//            a.code = j.code || '',
//            a.loading = !1,
//            a.imgHeight = (document.body.offsetWidth - 18) / 2,
//            0 == a.city || '' == a.city || 0 == a.city || void 0 == a.city ? (a.city = d.getInfo('city'), a.code = d.getInfo('code'), j.longitude = d.getInfo('longitude') + '', j.latitude = d.getInfo('latitude') + '', c.get('/zmw/weixin/get_location?longitude=' + d.getInfo('longitude') + '&latitude=' + d.getInfo('latitude')).success(function (b) {
//                angular.isObject(b) && (a.city = b.city, a.code = b.city_code, j.city = b.city, j.code = b.city_code + '', j.town = b.district, j.province = b.province, d.setInfo('city', b.city), d.setInfo('code', b.city_code), d.setInfo('town', b.district), d.setInfo('province', b.province))
//            }), j.longitudeD = d.getInfo('longitudeD') + '', j.latitudeD = d.getInfo('latitudeD') + '', c.get('/zmw/weixin/get_location?longitude=' + d.getInfo('longitudeD') + '&latitude=' + d.getInfo('latitudeD')).success(function (a) {
//                angular.isObject(a) && (j.cityD = a.city, j.codeD = a.city_code + '', j.townD = a.district, j.provinceD = a.province, d.setInfo('cityD', a.city), d.setInfo('codeD', a.city_code), d.setInfo('townD', a.district), d.setInfo('provinceD', a.province))
//            })) : (d.setInfo('city', j.city), d.setInfo('code', j.code), d.setInfo('town', j.town), d.setInfo('province', j.province), d.setInfo('longitude', j.longitude), d.setInfo('latitude', j.latitude));
//        var m = g.search().source;
//        'share' === m && (a.backPath = 'designer'),
//            a.products = [];
//        var n = !1;
//        a.loaded = !1,
//            c.get('/tech/findById?id=' + k + '&user_id=' + d.getInfo('user_id')).success(function (b) {
//                if (console.log(b), 'ok' == b.message) {
//                    a.art = b.data;
//                    var c = g.search().source;
//                    a.showAppload = !0;
//                    'share' != c && e.showGuide('designer');
//                }
//            }).error(function () {
//            }),
//            a.addToFav = function () {
//                return d.getInfo('user_id') ? (n || (n = !0, c.get('/zmw/weixin/artisan_fav?user_id=' + d.getInfo('user_id') + '&artisan_id=' + a.art.artisan_id + '&is_fav=' + !a.isFaved).success(function (b) {
//                    'ok' == b.result ? a.isFaved = !a.isFaved : alert('收藏美容师失败!'),
//                        setTimeout(function () {
//                            n = !1
//                        }, 500)
//                }).error(function () {
//                    setTimeout(function () {
//                        n = !1
//                    }, 500)
//                })), void 0) : (alert('想收藏这个漂亮的美容师么？您还未关注“大脸猫”公众账号，还不能收藏，赶紧去关注吧！更多美容，美容师任你收藏哦！'), !1)
//            },
//            a.showBigImg = function (b, c) {
//                var d = a.art.images,
//                    e = [];
//                angular.forEach(d, function (a) {
//                    e.push(a.artisan_photo)
//                }),
//                    f.creatImgShow(e, b),
//                    c.stopPropagation()
//            };
//        var o = function () {
//            var b = 40,
//                e = d.getInfo('code'),
//                f = d.getInfo('longitude'),
//                g = d.getInfo('latitude');
//            c.get('/item/find?psize=' + b + '&city=' + e + '&longitude=' + f + '&latitude=' + g + '&techId=' + k + '&pno=' + l++).success(function (c) {
//                'ok' == c.message && (c.data.forEach(function (b) {
//                    a.products.push(b)
//                }), c.data.length > 0 ? (a.loading = !1, a.loaded = c.data.length >= b ? !0 : !1) : (a.loadingMsg = '没有更多', i(function () {
//                    a.loading = !1,
//                        a.hasMore = !1,
//                        a.loaded = !1
//                }, 2000)))
//            }).error()
//        };
//        a.$on('loadmore', function () {
//            a.loading || 0 === a.products.length || (a.loading = !0, a.loadingMsg = '加载更多', o('all'))
//        }),
//            o(),
//            a.loadmoreHandler = function () {
//                a.loading || 0 === a.products.length || (a.loading = !0, o('all'))
//            }
//    }
//]);
// 产品详情
dlmModule.controller('ItemShow', [
    '$scope',
    '$routeParams',
    '$http',
    '$location',
    'Order',
    'User',
    'Util',
    '$cookieStore',
    function (a, b, c, d, e, f, g, h) {
        var itemId = b.itemId;
        var tiId = b.tiId;
        if (b.techId != -1) {
            c.get('/tech/findById?id=' + b.techId).success(function (result) {
                var od = {};
                od.tech_name = result.data.name;
                od.tech_id = result.data.id;
                od.tech_headImg = result.data.tech_headImg;
                od.tech_name = result.data.name;
                h.put('order', od);
            });
        }else{
            h.put('order',{});
        }
        a.isSaved = !1;
        a.backPath = '';
        a.left = function () {
            var multiply = $('#multiply');
            var num = parseInt(multiply.val());
            var min = parseInt(multiply.attr('min'));
            var max = parseInt(multiply.attr('max'));
            if (num >= 2) {
                a.order.num = num - 1;
                a.order.sumPrice -= a.item.price;
                a.order.sumSpendTime -= parseInt(a.item.spend_time);
            }
        };
        a.right = function () {
            var multiply = $('#multiply');
            var num = parseInt(multiply.val());
            var min = parseInt(multiply.attr('min'));
            var max = parseInt(multiply.attr('max'));
            if (num <= max - 1) {
                a.order.num = num + 1;
                a.order.sumPrice += a.item.price;
                a.order.sumSpendTime += parseInt(a.item.spend_time);
            }
        };
        a.oStep1 = function () {
            if (h.get('order') == undefined) {
                h.put('order', {});
            }
            var od = h.get('order');
            od.sumPrice = a.order.sumPrice;
            od.isCoupon = 0;
            od.couponPrice = 0;
            od.userId = 1;
            od.cashPrice = a.order.sumPrice;
            od.items = [{
                'item_id': b.itemId,
                'item_name': a.item.item_name,
                'tiId':tiId,
                'num': a.order.num,
                'sumPrice': a.order.sumPrice
            }];
            h.put('order', od);
            if (od.tech_id == undefined) { //如果未选择店面
                window.location.href = "/#/selectTech";
            }else{
                window.location.href = "/#/oStep1";
            }
        };

        var i = !1,
            j = d.search().source;
        'share' === j && (a.backPath = 'index'),
            a.addOrder = function () {
                e.add({
                    product: a.product,
                    artisan: a.artisan
                }),
                    f.getInfo('mobile') ? d.path('/order/step/' + h + '/' + a.artisan.artisan_id) : (alert('请先绑定手机号'), d.path('/user/mobile'))
            },
            a.addFav = function (b) {
                return f.getInfo('user_id') ? b && a.isSaved ? (b(), void 0) : (i || (i = !0, c.get('/zmw/weixin/product_fav?product_id=' + h + '&user_id=' + f.getInfo('user_id') + '&is_fav=' + !a.isSaved).success(function (c) {
                    'ok' == c.result ? (a.isSaved = !a.isSaved, b && b()) : alert('收藏作品失败!'),
                        setTimeout(function () {
                            i = !1
                        }, 500)
                }).error(function () {
                    setTimeout(function () {
                        i = !1
                    }, 500)
                })), void 0) : (alert('想收藏这个漂亮的美容么？您还未关注“大脸猫”公众账号，还不能收藏，赶紧去关注吧！更多美容，美容师任你收藏哦！'), !1)
            },
            c.get('/item/findById?id=' + itemId + '&user_id=' + f.getInfo('user_id'))
                .success(function (b) {
                    if ('ok' == b.message) {
                        $("#tab-box1").html(b.data.flow);
                        $("#tab-box2").html(b.data.function);
                        $("#tab-box3").html(b.data.tips);
                        a.order = {};

                        a.item = b.data,
                            a.order.sumPrice = b.data.price,
                            a.order.num = 1,
                            a.order.itemId = b.data.item_id,
                            a.order.sumSpendTime = parseInt(b.data.spend_time),
                            a.artisan = b.data,
                            a.isSaved = b.is_fav,
                            a.carouselItems = b.data.main_img,
                            a.title = b.data.name,
                            window.weixinShareImgUrl = '/' + b.data.main_img,
                            window.weixinShareTitle = '喜欢！姐妹们快来看，我做的美容怎么样？';
                        var c = d.search().source;
                        'share' != c && g.showGuide('product')
                    }
                })
    }
]);

dlmModule.controller('SelectTechCtrl',
    function ($scope, $cookieStore, $http, User, city) {
        var order = $cookieStore.get('order');
        //查询有该项目的店面
        $http.get('tech/find?itemId=' +　order.items[0].item_id).success(function (b) {
            //alert(b.data);
            $scope.artis = b.data;
        });
        $scope.setTech = function (tech_id, tech_headImg, tech_name) {
            order.tech_id = tech_id;
            order.tech_headImg = tech_headImg;
            order.tech_name = tech_name;
            $cookieStore.put('order',order);
            window.location.href = "/#/oStep1";
        };
});

dlmModule.controller('OrderStep1Ctrl',
    function ($scope, $cookieStore, $http, User, city) {
        $scope.showAppload = !0;
        $scope.citys = city;
        $scope.dicts = city[0].dict;
        $scope.title = "填写订单信息";

        $http.get('addr/findLast').success(function (b) {
            console.log(JSON.stringify(b));
            $scope.addr = {};
            $scope.addr.phone = b.data.tel;
            $scope.addr.remark = b.data.remark;
            $scope.addr.contact = b.data.name;
            var addr = b.data.address.split(' ');
            $scope.addr.cityName = addr[0];
            $scope.addr.dictName = addr[1];
            $scope.addr.address = addr[2];
        });

        $scope.onblur = function (domId) {
            $('#' + domId).css({'display': 'none'});
        };
        $scope.nextStep = function () {
            if ($scope.addr.contact == undefined || $scope.addr.phone == '') {
                $('#warn_contact').css({'display': 'initial'});
                return;
            }
            $('#warn_dict').css({'display': 'none'});
            if ($scope.addr.phone == undefined || $scope.addr.phone == '') {
                $('#warn_phone').css({'display': 'initial'});
                return;
            }
            if ($scope.addr.cityName == undefined || $scope.addr.cityName == '') {
                $('#warn_city').css({'display': 'initial'});
                return;
            }
            $('#warn_city').css({'display': 'none'});
            if ($scope.addr.dictName == undefined || $scope.addr.dictName == '') {
                $('#warn_dict').css({'display': 'initial'});
                return;
            }
            if ($scope.addr.address == undefined || $scope.addr.phone == '') {
                $('#warn_address').css({'display': 'initial'});
                return;
            }

            if(!validatemobile($scope.addr.phone)){
                alert("手机号格式不正确!");
                return;
            }
            var addr = $cookieStore.get('addr');
            if(addr == undefined){
                addr = {};
            }
            addr.cityName = $scope.addr.cityName;
            addr.dictName = $scope.addr.dictName;
            addr.phone = $scope.addr.phone;
            addr.address = $scope.addr.address;
            addr.contact = $scope.addr.contact;
            addr.remark = $scope.addr.remark;
            $cookieStore.put('addr', addr);
            window.location.href = "/#/oStep2";
        };
    });
dlmModule.controller('OrderStep2Ctrl',
    function ($scope, $cookieStore, $http, $compile, User) {
        $scope.title = "填写时间";
        var order = $cookieStore.get('order');
        $scope.$on('$viewContentLoaded', function () {
            var days = makeTime();
            var dom = "";
            for (var i = 0; i < days.length; i++) {
                dom += '<td ng-click="findWT(' + i +',' + order.tech_id + ',\'' + days[i].day + '\')"><div><span>' + days[i].week + '</span></br><span>' + days[i].day + '</span></div></td>';
            }
            $($compile(dom)($scope)).appendTo("#days_tr");
            order.date = days[0].day;
            var now = new Date();
            $scope.findWT(0,order.tech_id,(now.getMonth()+1)+"/" + now.getDate());
        });
        $scope.findWT = function (th, techId, dateStr) {
            $('#days_tr td').each(function (v, value) {
                if(v == th){
                    $(value).addClass('active');
                }else{
                    $(value).removeClass('active');
                }
            });
            order = $cookieStore.get('order');
            var now = new Date();
            var minStr = now.getMinutes();
            var ds = now.getDate();
            if(now.getMinutes() < 10){
                minStr = "0" + now.getMinutes();
            }
            if(now.getDate() < 10){
                ds = "0" + now.getDate();
            }
            var nowDate = parseInt((now.getMonth() + 1) + "" + ds);
            var nowStr = parseInt(now.getHours()+1 + "" + minStr); //只能约一小时后的。
            var date = parseInt(dateStr.replace(":", "").replace("/", ""));

            if (techId == undefined) {   //没有选美容师,显示所有时间
                $.get('order/findAllWT', function (result) {
                    var html = "";
                    $.each(result.data, function (n, value) {
                        if (n == 0) {
                            html += "<tr>";
                        } else if (n == result.data.length) {
                            html += "</tr>"
                        } else if (n % 4 == 0) {
                            html += "</tr><tr>";
                        }
                        if (date <= nowDate && parseInt(value.time.replace(":", "").replace("/", "")) <= nowStr) {
                            html += '<td class="passed"><div>' + value.time + '</div></td>';
                        } else {
                            if(order.date == dateStr && order.time == value.time){
                                html += '<td class="nopassed" ng-click="selTime($event,\'' + dateStr + '\',\'' + value.time + '\')" ><div  style="background-color:#F6769E;">' + value.time + '</div></td>';
                            }else{
                                html += '<td class="nopassed" ng-click="selTime($event,\'' + dateStr + '\',\'' + value.time + '\')" ><div>' + value.time + '</div></td>';
                            }
                        }
                    });
                    html += "</tr>";
                    var time_body = $('#time_body');
                    time_body.empty();
                    $($compile(html)($scope)).appendTo("#time_body");
                });
            } else {   //选择美容师,显示该美容师有空的时间.
                $.get('order/findWT?techId=' + techId + '&date=' + dateStr, function (result) {
                    var html = "";
                    var skipNum = 0;
                    $.each(result.data, function (n, value) {
                        if (n == 0) {
                            html += "<tr>";
                        } else if (n == result.data.length) {
                            html += "</tr>"
                        } else if (n % 4 == 0) {
                            html += "</tr><tr>";
                        }
                        if((date <= nowDate && parseInt(value.time.replace(":", "").replace("/", "")) <= nowStr) || skipNum-- > 0){
                            html += '<td class="passed"><div>' + value.time + '</div></td>';
                        }else if(value.iw == null ) {
                            html += '<td class="passed"><div>' + value.time + '</div></td>';
                            skipNum = 3;
                        } else {
                            if(order.date == dateStr && order.time == value.time){
                                html += '<td class="nopassed" ng-click="selTime($event,\'' + dateStr + '\',\'' + value.time + '\')" ><div style="background-color:#F6769E;">' + value.time + '</div></td>';
                            }else{
                                html += '<td class="nopassed" ng-click="selTime($event,\'' + dateStr + '\',\'' + value.time + '\')" ><div>' + value.time + '</div></td>';
                            }
                        }
                    });
                    html += "</tr>";
                    var time_body = $('#time_body');
                    time_body.empty();
                    $($compile(html)($scope)).appendTo("#time_body");
                });
            }
        };
        $scope.selTime = function (event,date, time) {
            if(event.target.nodeName == 'DIV'){
                //alert($(event.target).parent().nextAll().length);
                //return;
                var order = $cookieStore.get('order');
                order.time = time;
                order.date = date;
                $cookieStore.put('order', order);
                $('#time_body tr td:not(.passed) div').each(function (v, value) {
                    $(value).css({'background-color':'#cacaca'});
                });
                $(event.target).css({'background-color':'#F6769E'});
            }
        };
        $scope.setTech = function (tech_id, tech_headImg, tech_name) {
            //添加美容师id
            order.tech_id = tech_id;
            order.tech_headImg = tech_headImg;
            order.tech_name = tech_name;
            $cookieStore.put('order',order);
            $scope.nextStep();
        };
        $scope.nextStep = function () {
            order = $cookieStore.get('order');

            if (order.date == undefined || order.time == undefined) {
                $('#tech_list').hide();
                $('#frmMain').show();
                alert('请先选择时间!');
                return;
            }
            if (order.tech_id == undefined) {
                $http.get('tech/findWT?date=' + order.date + '&time=' + order.time).success(function (b) {
                    console.log(JSON.stringify(b));
                    $scope.artis = b.data;
                });
                $scope.order = order;
                $('#tech_list').show();
                $('#frmMain').hide();
                return;
            }
            window.location.href = "/#/oStep3"
        };

    });

dlmModule.controller('OrderStep3Ctrl',
    function ($scope, $http, User, $cookieStore) {
        var order = $cookieStore.get('order');
        $scope.title = "提交订单";
        $scope.order = order;
        $scope.addr = $cookieStore.get('addr');
        $scope.couponId = 0;
        $scope.payWay = 1;
        $http.get('/ucoupon/find?isUseful=1').success(function (result) {
            $scope.ucoupon = result.data;
            var p = order.items[0].sumPrice;
            if($scope.ucoupon != undefined && $scope.ucoupon.length > 0){
                order.isCoupon = 1;
                $scope.couponId = result.data[0].id;
                p = order.items[0].sumPrice - $scope.ucoupon[0].price;
            }
            $scope.cashPrice = p >= 0?p:0;
            $scope.couponPrice = order.items[0].sumPrice -p;
        });

        $scope.nextStep = function () {
            $http.get('/order/add?techId=' + order.tech_id + '&beginDate=' + order.date + '&beginTime=' + order.time
                + '&address=' + JSON.stringify($scope.addr) + "&userId=" + order.userId + "&items=" + JSON.stringify(order.items)
                + '&sumPrice=' + order.sumPrice + "&isCoupon=" + order.isCoupon + "&couponPrice=" + $scope.couponPrice
                + '&cashPrice=' + $scope.cashPrice + '&couponId=' + $scope.couponId
            ).success(function (b) {
                    console.log('success');
                    window.location.href = "/#/user/order"
                });
        }
    });
dlmModule.controller('OrderDetailCtrl',
    function ($scope,$routeParams, $http, User, $cookieStore) {
        $http.get('/order/findById?orderId=' + $routeParams.orderId).success(function (b) {
            $scope.order = b.data;
        });
        //var order = $cookieStore.get('order');
        $scope.title = "订单详情";
        $scope.cancleOrder = function(){
            if(window.confirm('确认取消该订单？')){
                $http.get('/order/cancelOrder?id=' + $routeParams.orderId).success(function (b) {
                    alert('订单已经取消');
                    window.location.href = "/#/user/order"
                });
            }
        };
        //$scope.order = order;
        //$scope.addr = $cookieStore.get('addr');
        //$scope.couponId = 0;
        //$scope.payWay = 1;
        //$http.get('/ucoupon/find?isUseful=1').success(function (result) {
        //    $scope.ucoupon = result.data;
        //    var p = order.items[0].sumPrice;
        //    if($scope.ucoupon != undefined && $scope.ucoupon.length > 0){
        //        order.isCoupon = 1;
        //        $scope.couponId = result.data[0].id;
        //        p = order.items[0].sumPrice - $scope.ucoupon[0].price;
        //    }
        //    $scope.cashPrice = p >= 0?p:0;
        //    $scope.couponPrice = order.items[0].sumPrice -p;
        //});

        //$scope.nextStep = function () {
        //    $http.get('/order/add?techId=' + order.tech_id + '&beginDate=' + order.date + '&beginTime=' + order.time
        //        + '&address=' + JSON.stringify($scope.addr) + "&userId=" + order.userId + "&items=" + JSON.stringify(order.items)
        //        + '&sumPrice=' + order.sumPrice + "&isCoupon=" + order.isCoupon + "&couponPrice=" + $scope.couponPrice
        //        + '&cashPrice=' + $scope.cashPrice + '&couponId=' + $scope.couponId
        //    ).success(function (b) {
        //            console.log('success');
        //            window.location.href = "/#/user/order"
        //        });
        //}
    });

dlmModule.controller('UserHomeCtrl', [
    '$scope',
    '$http',
    'User',
    function (a, b, c) {
        a.userInfo = c.getInfo(),
        a.userInfo.id || c.getUserInfo()
    }
]);
dlmModule.controller('UserOrderCtrl', [
    '$scope',
    '$http',
    'User',
    'pageSize',
    'Util',
    '$timeout',
    '$route',
    '$location',
    function (a, b, c, d, e, f, g, h) {
        var j = 1;
        b.get('order/find?userId=1&psize=' + d + '&pno=' + j).success(function (result) {
            if(result.code == 0){
                a.orders = result.data;
            }else if(result.code == 100){
                window.location.href = "#/reg";
            }
        });
    }
]);

dlmModule.controller('CouponCtrl',function($scope,$http){
    $http.get('ucoupon/find?userId=1').success(function(result){
        if(result.code == 0){
            $scope.coupons = result.data;
        }else if(result.code == 100){
            window.location.href = "#/reg";
        }
    });
});

dlmModule.controller('regCtrl',function($scope,$http){
    var isSend = false;
    $scope.sendSMS = function(){
        var maxtime = 59;
        if($scope.phone != null && $scope.phone != undefined
            && validatemobile($scope.phone) && !isSend){
            isSend = true;
            var timer = setInterval(function() {
                if (maxtime >= 0) {
                    var seconds = Math.floor(maxtime % 60);
                    seconds = seconds >= 10 ? seconds : '0' + seconds;
                    --maxtime;
                    $('#begin').val(seconds+'秒').css({background: 'gray'});;
                }else {
                    clearInterval(timer);
                    $('#begin').val('获取验证码').css({background: '#F6769E'});
                    isSend = false;
                }
            }, 1000);
            $http.get('sms/sendRegSMS?phone=' + $scope.phone).success(function(result){
                //TODO 设置按钮不可用.
            });
        }else if(isSend){

        }else{
            alert('手机号输入错误,请重新输入!');
        }
    };

    $scope.checkCode = function(){
        if($scope.code != null && $scope.code != undefined){
            $http.get('sms/checkCode?code=' + $scope.code).success(function(result){
                if(result.code == 0){
                    alert('绑定成功，去个人中心查看优惠券!');
                    //window.location.href= '#/index';
                    window.location.href= '#/user/coupon';
                }else{
                    alert('手机号绑定失败!');
                }
            });
        }else{
            alert('验证码输入错误,请重新输入!');
        }

    };
});

////////////////////////////filter//////////////////////////////

dlmModule.filter('num2mi', function () {
    return function (a) {
        var b = '',
            c = parseFloat(a);
        if (1 > c) {
            var d = (a + '').split('.') [1].slice(0, 3);
            d = parseInt(d, 10),
                //b += '<strong>' + d + '</strong>米'
                b += d + '米'
        } else b += '<strong>' + c.toFixed(1) + '</strong>公里';
        return b
    }
});

dlmModule.filter('doubleStr', function () {
    return function (a) {
        return a + ".00";
    }
});

//////////////////////////service//////////////////////
dlmModule.service('User', [
    '$http',
    '$location',
    '$cookieStore',
    function (a, b, c) {
        var d = {
            info: {
                nick: '',
                city: '北京',
                code: 110100,
                longitude: 116.462623,
                latitude: 39.95676,
                codeD: 110100,
                longitudeD: 116.462623,
                latitudeD: 39.95676,
                mobile: '',
                addrs: []
            },
            getInfo: function (a) {
                return a ? this.info[a] || null : this.info
            },
            setInfo: function (a, b) {
                arguments.length > 1 ? this.info[a] = b : angular.extend(this.info, arguments[0])
            },
            getUserId: function () {
                var a = b.search().user_id;
                a ? (window.user_id = a, c.put('user_id', a)) : a = c.get('user_id'),
                a && (this.setInfo('user_id', a), this.getUserInfo())
            },
            getUserInfo: function () {
                var b = this,
                    c = b.getInfo('user_id');
                if (c) return a.get('/zmw/weixin/get_userinfo?user_id=' + b.getInfo('user_id')).success(function (a) {
                    if ('ok' == a.result) {
                        var c = a.userInfo.headerpic;
                        a.userInfo.avatar = c.indexOf('http') >= 0 ? a.userInfo.headerpic : '/zmw/' + a.userInfo.headerpic,
                        '' === a.userInfo.nick.trim() && (a.userInfo.nick = a.userInfo.mobile),
                            b.setInfo(a.userInfo)
                    } else alert('获取用户信息失败')
                })
            },
            getAddrs: function () {
                var b = this;
                return a.get('/zmw/weixin/get_common_address?user_id=' + b.getInfo('user_id')).success(function (a) {
                    'ok' == a.result && b.setInfo('addrs', a.address_info)
                })
            }
        };
        return d
    }
]);
dlmModule.service('SerData', function () {
    this.indexPageSize = 100
});
dlmModule.service('Order', [
    'User',
    '$http',
    function (a, b) {
        var c = {
            orderInfo: {},
            add: function (a) {
                this.orderInfo = a
            },
            getProductInfo: function (c) {
                var d = this;
                return this.orderInfo.product ? this.orderInfo : b.get('/zmw/weixin/product_detail?product_id=' + c + '&user_id=' + a.getInfo('user_id')).success(function (a) {
                    'ok' == a.result && d.add({
                        product: a.product,
                        artisan: a.artisanShortInfo
                    })
                })
            },
            clean: function () {
                this.orderInfo = {}
            },
            post: function (c) {
                var d = this.orderInfo.product,
                    e = this.orderInfo.artisan,
                    f = angular.extend({
                        product_price: d.zhima_price,
                        product_id: d.product_id,
                        artisan_id: e.artisan_id,
                        order_from: 'weixin',
                        user_name: a.getInfo('nick'),
                        user_contact: a.getInfo('mobile'),
                        order_time_type: 1,
                        user_id: a.getInfo('user_id'),
                        order_time: (new Date).getTime()
                    }, c);
                b({
                    method: 'GET',
                    url: '/zmw/weixin/submit_order',
                    params: f
                }).success(function (a) {
                    console.log(a)
                })
            }
        };
        return c
    }
]);

dlmModule.service('imgShow', [
    'Util',
    function (a) {
        this.creatImgShow = function (b, c) {
            this.sWidth = document.body.offsetWidth;
            var d = '<ul class="show-bigimg">';
            this.index = c,
                this.imgCount = b.length;
            var e = this;
            return angular.forEach(b, function (a, b) {
                d += '<li style="-webkit-transform: translateX(' + 100 * b + '%);width:' + e.sWidth + 'px"><span><img src="http://meijia.365pp.com/zmw/' + a + '"></span></li>'
            }),
                d += '</ul>',
                this.wrap = a.showBigImg(),
                this.wrap.html(d),
                this.box = this.wrap.find('ul'),
                this.box.css({
                    width: this.sWidth * this.imgCount + 'px'
                }),
                this.setTrans(c),
                this.bindEvent(),
                this
        },
            this.setTrans = function (a, b) {
                b && this.box.addClass('animate'),
                    this.box.css({
                        '-webkit-transform': 'translateX(-' + a * this.sWidth + 'px)'
                    })
            },
            this.bindEvent = function () {
                var a = this,
                    b = !1,
                    c = {};
                this.box.on('touchstart', function (a) {
                    if (!b && a.touches.length > 0) {
                        var d = a.touches[0];
                        b = !0,
                            c.startX = d.pageX,
                            c.startY = d.pageY,
                            c.stepsX = c.stepsY = 0
                    }
                }).on('touchmove', function (d) {
                    if (b) {
                        {
                            var e = d.touches[0],
                                f = e.pageX - c.startX;
                            e.pageY - c.startY
                        }
                        c.moveX = Math.abs(f),
                            c.directionX = f > 0 ? !0 : !1,
                            a.box.css({
                                '-webkit-transform': 'translateX(' + -(a.sWidth * a.index - f) + 'px)'
                            }),
                            d.preventDefault()
                    }
                }).on('touchend', function () {
                    b && (c.moveX > 30 && (a.index = c.directionX ? --a.index <= 0 ? 0 : a.index : ++a.index >= a.imgCount - 1 ? a.imgCount - 1 : a.index), a.setTrans(a.index, !0))
                }).on('webkitTransitionEnd', function () {
                    b = !1,
                        a.touchs = {},
                        a.box.removeClass('animate')
                })
            }
    }
]);
////////////////////////factory///////
dlmModule.factory('Util', [
    function () {
        function a(a) {
            return d || (d = angular.element(document.createElement('div'))),
                angular.element(document.getElementsByTagName('body')).append(d),
                d.attr('class', 'mask'),
            a && setTimeout(function () {
                d.on('click', c)
            }, 600),
                d
        }

        function b() {
            var a = 0,
                b = 0,
                c = 0;
            return document.documentElement && document.documentElement.scrollTop ? a = document.documentElement.scrollTop : document.body && (a = document.body.scrollTop),
                b = document.body.clientHeight && document.documentElement.clientHeight ? document.body.clientHeight < document.documentElement.clientHeight ? document.body.clientHeight : document.documentElement.clientHeight : document.body.clientHeight > document.documentElement.clientHeight ? document.body.clientHeight : document.documentElement.clientHeight,
                c = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight),
            {
                scrollTop: a,
                clientHeight: b,
                scrollHeight: c
            }
        }

        function c() {
            d && (d.off('click', c), d.html('').remove())
        }

        var d;
        return {
            time2day: function (a) {
                var b = new Date(a);
                return {
                    year: b.getFullYear(),
                    mon: b.getMonth() + 1 < 10 ? '0' + (b.getMonth() + 1) : b.getMonth() + 1,
                    day: b.getDate() < 10 ? '0' + b.getDate() : b.getDate(),
                    hour: b.getHours() < 10 ? '0' + b.getHours() : b.getHours(),
                    min: b.getMinutes() < 10 ? '0' + b.getMinutes() : b.getMinutes()
                }
            },
            showGuide: function (b) {
                var c = window.localStorage.getItem(b);
                c || (window.localStorage.setItem(b, !0), a(!0).addClass(b))
            },
            showBigImg: function () {
                return a(!0)
            },
            isIOS7: function () {
                var a = window.navigator.userAgent;
                return /iphone\s+os\s+7_?/gi.test(a)
            },
            showMsg: function () {
                a(!1)
            },
            removeMask: c,
            getWidth_height: b
        }
    }
]);